package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.mapper.ApUserMapper;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.service.IApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserLoginServiceimpl implements IApUserLoginService {

    @Resource
    private ApUserMapper apUserMapper;


    /**
     *登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(LoginDto dto) {

        if (StringUtils.isEmpty(dto.getPassword()) || StringUtils.isEmpty(dto.getPhone())){
            log.error("手机号或者密码为空");
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        LambdaQueryWrapper<ApUser> wrapper = Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getPhone, dto.getPhone());
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if (null == apUser){
            log.error("手机号或者密码错误");
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        String password = dto.getPassword();
        String salt = apUser.getSalt();
        String pass = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!pass.equals(apUser.getPassword())){
            log.error("手机号或者密码错误");
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        String token = AppJwtUtil.getToken(apUser.getId().longValue());

        Map<String,Object> map = new HashMap<>();
        map.put("user",ApUser.builder().id(apUser.getId()).name(apUser.getName()).phone(apUser.getPhone()).build());
        map.put("token",token);

        return map;
    }
}
